# -*- coding: utf-8 -*-
"""
@Time : 2024/5/3 1:39 PM
@Author: imamhusan
@Des: 微信用户
"""
from fastapi import APIRouter, Body
from core.Response import success, fail
from models.wx_user import WxUser
from core.Auth import create_token
import os
import requests

router = APIRouter(prefix='/mp')


@router.post('/login', description='微信小程序登录')
async def login(code: str = Body(..., embed=True), xuser: int = Body(..., embed=True)):
    try:
        url = 'https://api.weixin.qq.com/sns/jscode2session'
        params = {
            "appid": os.getenv('MP_APPID', 'wx12369ab50490c9a3'),
            "secret": os.getenv('MP_SECRET', '6e1e41f55f031fed2c12da17ca9ac3b2'),
            "js_code": code,
            "grant_type": "authorization_code"
        }

        res = requests.get(url=url, params=params).json()
        openid = res.get('openid', None)

        # 检测是否存在该用户
        wx_user = await WxUser.get_or_none(openid=openid)

        if not wx_user:
            # 创建新用户
            wx_user = await WxUser.create(
                openid=openid,
                xuser=xuser,
                nickName='Ozhas_User',
                avatarUrl='https://mms0.baidu.com/it/u=770777987,2404620017&fm=253&app=138&f=JPEG?w=178&h=173'
            )

        token = create_token(data={
            'user_id': wx_user.pk,
            'user_type': 'mp'
        })

        return success(data={'token': token, 'id': wx_user.pk}, msg='登录成功')

    except Exception as e:
        return fail(str(e))
